import {Component, Input, OnInit} from '@angular/core';
import {DocApi} from '../../entity/doc-api';
import {EntityRef} from '../../entity/entity-ref';
import {EnvItem} from '../../entity/env-item';
import {UserService} from '../../service/user.service';
import {User} from '../../entity/user';
import {Artifact} from '../../entity/artifact';
import {ParamEntity} from '../../entity/param-entity';
import {Entity} from '../../entity/entity';
import {DocService} from '../../service/doc.service';

@Component({
    selector: 'app-page-api-rest',
    templateUrl: './page-api-rest.component.html',
    styleUrls: ['./page-api-rest.component.css']
})
export class PageApiRestComponent implements OnInit {
    private _api: DocApi;

    get api(): DocApi {
        return this._api;
    }

    @Input()
    set api(value: DocApi) {
        this._api = value;
        this.initRequestParams();
    }

    /**
     * 接口版本号
     */
    @Input()
    apiVersion: string | number;

    @Input()
    artifact: Artifact;

    /**
     * 实体类参数，需要展示内部结构
     */
    @Input()
    paramEntities: ParamEntity[];

    @Input()
    requestBodys: EntityRef[];

    requestHeaderParameters: EntityRef[] = [];

    requestParameters: EntityRef[] = [];

    body: EntityRef;
    bodyEntity: Entity;

    @Input()
    response: EntityRef;

    @Input()
    envs: EnvItem[];

    user: User;

    constructor(
        private userService: UserService,
        private docService: DocService
    ) {
        this.userService.userObservable.subscribe((user: User) => {
            if (user && user.name) {
                this.user = user;
            } else {
                this.user = null;
            }
        });
    }

    ngOnInit() {
    }

    private initRequestParams(): EntityRef[] {
        if (!this._api || !this._api.requestParams) {
            return [];
        }
        this.requestHeaderParameters = [];
        this.requestParameters = [];
        this.bodyEntity = null;
        this.body = null;
        this._api.requestParams.forEach(param => {
            if (param.annotation === '@RequestHeader') {
                this.requestHeaderParameters.push(param);
            } else if (param.annotation === '@RequestBody') {
                this.body = param;
                this.bodyEntity = this.docService.getEntity(param.entityName);
            } else {
                this.requestParameters.push(param);
            }
        });
    }
}
